﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PeoplesJukebox.Core.Interfaces;
using PeoplesJukebox.Core.MediaItems;
using System.Threading;
using PeoplesJukebox.Core.Logging;
using Alvas.Audio;
using System.IO;

namespace PeoplesJukebox.Core.Players
{
    public class AlvasAudioPlayer : IMediaPlayer
    {
        private static Track _currentTrack;
        private static PlayerEx _player;

        static AlvasAudioPlayer()
        {
            _player = new PlayerEx(true);
            _player.Done += new PlayerEx.DoneEventHandler(OnPlayerDone);
        }

        public Track CurrentTrack
        {
            get { return _currentTrack; }
        }

        public void Start()
        {
            PlayNext();
        }

        static void PlayNext()
        {
            Track nextTrack = PeoplesJukeboxService.GetNextTrack();
            if (nextTrack != null)
            {
                //TODO - add logging
                try
                {
                    StopInternal();
                    Log.Info("AlvasAudioPlayer.PlayNext, new URL={0}", nextTrack.Uri);
                    ThreadPool.QueueUserWorkItem(PlayCallback, nextTrack);                    
                }
                catch (Exception ex)
                {
                    Log.Error("AlvasAudioPlayer.PlayNext errored: {0}", ex.Message);
                }
                _currentTrack = nextTrack;
            }
        }

        static void PlayCallback(object state)
        {
            Log.Info("AlvasAudioPlayer.PlayCallback called");
            Track track = (Track)state;
            using (WaveReader wr = new WaveReader(File.OpenRead(track.Uri)))
            {
                IntPtr format = wr.ReadFormat();
                byte[] data = wr.ReadData();
                _player.OpenPlayer(format);
                _player.AddData(data);
            }
            _player.StartPlay();
            Log.Info("AlvasAudioPlayer.PlayCallback, called StartPlay()");
        }

        static void OnPlayerDone(object sender, DoneEventArgs e)
        {
            Log.Info("AlvasAudioPlayer.OnPlayerDone");
            PlayNext();
        }

        public void Skip()
        {
            PlayNext();
        }

        public void Stop()
        {
            StopInternal();
        }

        static void StopInternal()
        {
            if (_player != null)
            {
                _player.ClosePlayer();
            }
        }
    }
}
